/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  themes_default
 */
var numPage = 1;
var nbImage = 24;
var folderRoot;
var folderId;
var folderLang = "fr";
var actionAddImg;

function getContextMenu()
{
    $(".contextMenu").html($("#sliderMenuContextMenu").html());
    if($(".contextMenu li").length > 1)
    {
        $(".contextMenu li:first").addClass("addMedia");
    }

    $(".contextMenu li:last").addClass("addFolder");
}

function loadFolderContent(selectedId)
{
	$.ajax({
		url: "?module=medias&action=block_MceFolderContent",
		data: "folderId="+folderId+"&folderLang="+folderLang+"&nbImage="+nbImage+"&numPage="+numPage+'&selectedId='+selectedId,
        async: false,
		beforeSend: function()
		{
            $("#loaderContainer").show();
			$("#pagination img").unbind();
			$("#pagination select").unbind();
		},
		success: function(response)
		{            
	 		$("#content").html(response);

            if(selectedId != null && $('#numPage').text() != '0')
            {
                numPage = $('#numPage').text();
            }
            
			catchImageClick();
			pagination();
            getContextMenu();

            window.location.hash = folderLang + '/' + folderId;
            
			if(selectedId != null)
			{
				folder = "#"+folderLang+"_"+selectedId;
				$(folder).children(".image").addClass("imageSelected");
				$(folder).children(".imageTitle").children(".imageTitleText").addClass("imageTitleSelected");
                $('#isImg').text('false');
                loadMediaDetails(selectedId, folderLang);
			}
            $('#folderContent').height($(window).height()-73);

            $("#loaderContainer").hide();
		}
	});	
}

function pagination()
{	
	var nbMedia = parseInt($("#nbMedia").text());

	$.ajax({
		url: "?module=medias&action=block_McePagination",
		data: "nbMedia="+nbMedia+"&nbImage="+nbImage+"&numPage="+numPage,
		success: function(response)
		{
	 		$("#pagination").html(response);
	 		
	 		if(response != "")
	 		{	 					 		
		 		var nbPageTot = $("#nbPageTot").text();

		 		$("#leftArrow, #rightArrow").click(function(event){
                    event.preventDefault();
		 			numPage = $(this).attr("id") == "leftArrow" ? parseInt(numPage) - 1 : parseInt(numPage) + 1;
		 			loadFolderContent();
		 		});
		 		
		 		$("#nbImage").change(function(){
		 			nbImage = parseInt($(this).val());
		 			loadFolderContent();
		 		});
		 		
		 		$("#pagination select[name=nbPage]").change(function(){
		 			numPage = parseInt($(this).val());
		 			loadFolderContent();
		 		});
		 		
		 		if(numPage <= 1 && nbPageTot > 1)
		 		{
		 			$("#leftArrow").hide().unbind();
		 		}
		 		
		 		if(nbPageTot > 1 && numPage >= nbPageTot)
		 		{
                    $("#rightArrow").hide().unbind();
		 		}
		 		
		 		if(nbPageTot > 1 && numPage > nbPageTot)
		 		{
		 			numPage = 1;
		 			loadFolderContent();
		 		}
	 		}
		}
	});
}

function save()
{
	var result = "";
	var style = "";
	
	if($("#formAlt").val() != "")
	{
		result += 'alt="' + $("#formAlt").val() + '" ';		
	}
	
	if($("#formTitle").val() != "")
	{
		result += 'title="' + $("#formTitle").val() + '" ';		
	}
	
	if($("#formAlign").val() != "none")
	{
        style += 'float: '+$("#formAlign").val()+'; ';
	}
	
	if($("#formMarginTop").attr('value') != "" || $("#formMarginBottom").attr('value') != "" || $("#formMarginLeft").attr('value') != "" || $("#formMarginRight").attr('value') != "")
	{
		var marginTop = 0, marginBottom = 0, marginLeft = 0, marginRight = 0;
		
		if($("#formMarginTop").attr('value') != "")
		{
			marginTop = $("#formMarginTop").attr('value')+"px";
		}
		
		if($("#formMarginBottom").attr('value') != "")
		{
			marginBottom = $("#formMarginBottom").attr('value')+"px";
		}
		
		if($("#formMarginLeft").attr('value') != "")
		{
			marginLeft = $("#formMarginLeft").attr('value')+"px";
		}
		
		if($("#formMarginRight").attr('value') != "")
		{
			marginRight = $("#formMarginRight").attr('value')+"px";
		}

		style += "margin: " + marginTop + " " + marginRight + " " + marginBottom + " " + marginLeft + "; ";
	}	
	
	if($('#formBorderWeight').attr('value') != "")
	{
		style += "border: " + $('#formBorderWeight').attr('value') + "px solid " + $('#hexColor').text();
	}
	
	if(style != "")
	{
		result += 'style="' + style + '" ';
	}
	
	if($("#formClasses").attr('value') != "")
	{
		result += 'class="' + $("#formClasses").attr('value') + '" ';
	}	

    var type = $("#type").html();
    var str = $("#path").html();
    var imgId = $("#pictureId").html();

	if(type == "img")
	{
        if(actionAddImg == "tinyMce")
        {
            str += $("#sizes option:selected").val();
            image = '<img src="'+str+'?'+Math.floor(Math.random()*1111)+'" id="picture_'+imgId+'"'+result+' />';
            var win = tinyMCEPopup.getWindowArg("editor");
            win.execCommand('mceInsertContent', false, image);
        }
        else if(actionAddImg == "image")
        {
            window.opener.saveImg(imgId);
        }
	}

    //For tinyMce, when it's file
    if(actionAddImg == "tinyMce" && type == "fic")
    {
        texte = $("#formTexte").val();
        target =  $("#formCible").val();
        title = $("#formTitle").val();
        link = '<a href="{mediaUrl docId='+imgId+' lang=\''+folderLang+'\'}" target="'+target+'" title="'+title+'">'+texte+'</a>';
        var win = tinyMCEPopup.getWindowArg("editor");
        win.execCommand('mceInsertContent', false, link);
    }

    //For linked media
    if(actionAddImg == "media")
    {
        window.opener.linkImg(imgId, "media", "link");
    }

	window.close();
}

function deleteDocument(docId, docLang)
{
	$.ajax({
		url:'?module=backoffice&action=block_DeleteGeneric&docId='+docId+'&docLang='+docLang,
		async: false,
		success: function(msg)
		{
			if(msg != "false")
			{
				var regExp = /[0-9]+/;
				var tabLink = msg.split("/");
				if(regExp.test(tabLink[tabLink.length-1]) == false)
				{
					tabLink[tabLink.length-1] = folderRoot;
					tabLink[tabLink.length-2] = folderLang;
				}

				$("#mediaDetail").html('<div id="mediaDetailMenu">&nbsp;</div>');
				$.nyroModalRemove();
                reloadSlideMenuContent(tabLink[tabLink.length-2]+'/'+tabLink[tabLink.length-1]);
                
				return false;
			}
		}
	});
}

function moveSelection(num)
{
	$(".image").removeClass("imageSelected");
	$(".imageTitleText").removeClass("imageTitleSelected");
	$("."+num).children(".image").addClass("imageSelected");
	$("."+num).children(".imageTitle").children(".imageTitleText").addClass("imageTitleSelected");
	params = $("."+num).attr("id").split("_");
	loadMediaDetails(params[1], params[0]);
}

function catchImageClick()
{
	if($(".image").length)
	{
		$(".imageContainer div").click(function(event){
            if($(this).hasClass('imageSelected'))
            {
                $('#content .selected').removeClass('selected').css('height','');
                $('.imageSelected').removeClass('imageSelected');
                $('#mediaDetail').remove();
            }
            else
            {
                params = $(this).parent().attr("class").split(" ");
                moveSelection(params[1]);
            }
		});
	}
}

function loadMediaDetails(docId, docLang)
{
    docLang = docLang.toLowerCase();
	$.ajax({
        async: false,
		url: "?module=medias&action=block_MceMediaDetail",
		data: "docId="+docId+"&docLang="+docLang+"&actionAddImg="+actionAddImg+"&isImg="+$('#isImg').text(),
        beforeSend: function()
        {
            if($('#mediaDetail').is(':visible')){$("#mediaDetail").remove();}
            $('#content .selected').removeClass('selected').css('height','');
            $('#'+docLang+'_'+docId).addClass('selected').append('<div id="mediaDetail"></div>');
            $("#loaderContainer").show();
        },
		success: function(response)
		{
            $('#mediaDetail').html(response);
            if($.browser.msie)
                $('#content .selected').css('height',$('#mediaDetail').height() + 66);
            else
                $('#content .selected').css('height',$('#mediaDetail').height() + 106);

            resizeMediaDetails();
            enableColorPicker();
            catchCloseClick();

            $("#loaderContainer").hide();
		}
	});
}

function catchCloseClick()
{
    $('#mediaCloseButton').click(function(){
        $('#content .selected').removeClass('selected').css('height','');
        $('.imageSelected').removeClass('imageSelected');
        $('#mediaDetail').remove();
    });
}

function previewPicture()
{
	var fileName = $("#sizes option:selected").val(), docId = $("#pictureId").text(), docLang = $("#pictureLang").text();
	centeredPopup("index.php?module=medias&action=block_mceMediaView&docId=" + docId + "&docLang=" + docLang + "&filename=" + fileName, fileName, 800, 600);
}
                
function enableColorPicker()
{
	$('#colorSelector').ColorPicker({
		color: '#000000',
		onShow: function (colpkr) {
			$(colpkr).fadeIn(500);
			return false;
		},
		onHide: function (colpkr) {
			$(colpkr).fadeOut(500);
			return false;
		},
		onChange: function (hsb, hex, rgb) {
			$('#colorSelector div').css('backgroundColor', '#' + hex);
			$('#hexColor').text('#' + hex);
		}
	});	
}

function loadPictureParams(dom, n)
{
	srcAttr = dom.getAttrib(n, 'src');
	alt = dom.getAttrib(n, 'alt');
	title = dom.getAttrib(n, 'title');
	style = dom.getAttrib(n, 'style');
	classe = dom.getAttrib(n, 'class');
	styles = style.split(";");
	
	source = src.split("/");
	name = source[source.length-1];
	attrs = name.split("?");
	picName = attrs[0];

	$("#sizes option[value="+picName+"]").attr("selected", "selected");

	for( var i in styles)
	{
		params = styles[i].split(": ");
		paramName = $.trim(params[0]);
		paramValue = $.trim(params[1]);

		switch(paramName)
		{
			case("float"):
                $('#align'+paramValue).addClass('selectedAlignement');
                $('#formAlign').val(paramValue);
			break;
			
			case("margin"):
				margins = paramValue.split(" ");
				
				$("#formMarginTop").attr("value", margins[0].replace("px", ""));
				$("#formMarginRight").attr("value", margins[1].replace("px", ""));
				$("#formMarginBottom").attr("value", margins[2].replace("px", ""));
				$("#formMarginLeft").attr("value", margins[3].replace("px", ""));
			break;
			
			case("border"):
				borderParams = paramValue.split(" ");
				
				$("#formBorderWeight").attr("value", borderParams[0].replace("px", ""));
				$("#selectorBg").css("background-color", borderParams[2]);
				$("#hexColor").text(borderParams[2]);
			break;
		}
	}
	
	$("#formAlt").val(alt);
	$("#formTitle").val(title);
	$("#formClasses").val(classe);
}

function research()
{
	var delayed;
	$("#boSearch input").keyup(function(event)
	{
	    clearTimeout(delayed);
	    var value = this.value;
	    
	    if(value)
	    {
	        delayed = setTimeout(function() {
	    		$.ajax({
	    			url: "?module=medias&action=block_MceFolderContent",
	    			data: "folderId="+folderId+"&folderLang="+folderLang+"&search="+value,
	    			beforeSend: function()
	    			{
	    				$("#loaderContainer").show();
	    			},
	    			success: function(response)
	    			{
	    		 		$("#content").html(response);
	    				catchImageClick();
	    				$("#pagination").html("");
                        $('#folderContent').height($(window).height()-73);
                        resizeMediaDetails();
	    				$("#loaderContainer").hide();
	    			}
	    		});
	        }, 500);
	    }
	    else
	    {
	    	loadFolderContent();
	    }
	});
}

function newSrc(imgPath, value)
{
    var tab = imgPath.split("/");
    tab.splice(tab.length-1,1,value);
    imgPath = tab.join("/");
    return imgPath;
}

function initBrowser()
{
    actionAddImg = window.opener.actionAddImg;

    if(actionAddImg == "tinyMce")
    {
        var ed = tinyMCEPopup.editor;
        var dom = ed.dom;
        var n = ed.selection.getNode();
    }
   
    var hash = window.location.hash.replace(/^.*#/, "");

    if(n != null && n.nodeName == 'IMG')
    {        
        src = dom.getAttrib(n, 'src');
        id = dom.getAttrib(n, 'id');
        params = src.split('/');
        pictureParams = id.split('_');
        tabLength = params.length;
        folderId = params[tabLength-3];
        folderLang = params[tabLength-2];

        window.location.hash = folderLang.toUpperCase()+"/"+folderId;
        
        reloadSlideMenuContent(window.location.hash);
        loadFolderContent(pictureParams[1]);
        loadPictureParams(dom, n);
    }
    else if(n != null && n.nodeName == 'A')
    {
        src = dom.getAttrib(n, 'href');
        var reg1 = new RegExp('docId=([0-9]+)', "g");
        var reg2 = new RegExp('lang=\'([a-zA-Z]+)\'', "g");

        folderId = reg1.exec(src)[1];
        folderLang = reg2.exec(src)[1].toLowerCase();

        reloadSlideMenuContent(folderLang+"/"+folderId);
        loadFolderContent(folderId);
    }
    else
    {
        if(hash != "")
        {
            params = hash.split("/");
            folderId = params[1];
            folderLang = params[0].toLowerCase();
            reloadSlideMenuContent(folderLang+"/"+folderId);
            loadFolderContent(folderId);
        }
        else
        {
            reloadSlideMenuContent('');
            catchImageClick();
            $('#folderContent').height($(window).height()-73);
            if($('#mediaDetail').css('display') != 'none')
            {
                resizeMediaDetails();
            }
        }
    }
}

/**
 * Ouvre une popup centrée
 * @param {String} windowURL
 * @param {String} windowName
 * @param {Integer} windowWidth
 * @param {Integer} windowHeight
 * @param {Boolean} hasScrollbars
 * @param {Boolean} isResizable
 * @param {Boolean} hasMenubar
 * @param {Boolean} hasToolbar
 * @param {Boolean} hasAddressbar
 * @param {Boolean} hasStatusbar
 * @param {Boolean} isFullscreen
 */
function centeredPopup(windowURL, windowName, windowWidth, windowHeight, hasScrollbars, isResizable, hasMenubar, hasToolbar, hasAddressbar, hasStatusbar, isFullscreen) 
{
  var windowLeft = (screen.width - windowWidth) / 2;
  var windowTop = (screen.height - windowHeight) / 2;
  var windowProperties = 'height=' + windowHeight + ',width=' + windowWidth + ',top=' + windowTop + ',left=' + windowLeft + ',scrollbars=' +hasScrollbars + ',resizable=' + isResizable + ',menubar=' + hasMenubar + ',toolbar=' + hasToolbar + ',location=' + hasAddressbar + ',statusbar=' + hasStatusbar + ',fullscreen=' + isFullscreen + '';
  var objwindow = window.open(windowURL, windowName, windowProperties)
    if (parseInt(navigator.appVersion) >= 4) {
      objwindow.window.focus();
    }
}

function liveQueryTooltips()
{
	$('.toolTip:not(img)').livequery(function()
	{
        if($(this))
		$(this).tooltip(
		{ 
		    track: true, 
		    delay: 1000,
		    showURL: false, 
		    fixPNG: true, 
		    showBody: " - ", 
		    extraClass: "fancy", 
		    top: -5, 
		    left: 5
		})
	});

 $('img.toolTip').livequery(function()
	{
        $(this).tooltip(
		{
		    track: false,
		    delay: 0,
		    showURL: false,
		    fixPNG: true,
		    showBody: " - ",
		    extraClass: "fancy",
		    top: -5,
		    left: 5
		})
    });
}

/**
 * Display modal window
 *
 * @param {String} href
 * @param {Boolean} noSessionCheck
 */
function showModal(href)
{
	$.nyroModalManual({
		url: href,
		minHeight: 105,
		minWidth: 300,
		modal: true,
		bgColor: '#CCCCCC',
		showBackground: function(elts, settings, callback){
			elts.bg.css("opacity", "0.8");
			callback();
		},
		showLoading: function(elts, settings, callback)
		{
			elts.loading.hide();
			callback();
		},
        endFillContent: function(elts, settings){
            if($('#modalContent').hasClass('withoutFooter'))
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
            else
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
        },
        endResize: function(elts, settings){
            if($('#modalContent').hasClass('withoutFooter'))
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
            else
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
        },
		showContent: function(elts, settings, callback) {
		  elts.contentWrapper
		    .css({ // Reset the CSS at the start position
		      marginTop: (-100/2 + settings.marginScrollTop)+'px',
		      marginLeft: (-100/2 + settings.marginScrollLeft)+'px',
		      height: '30px',
		      width: '30px',
		      opacity: 0
		    })
		    .show()
		    .css({ // Set the width
		      width: settings.width+'px',
		      marginLeft: (settings.marginLeft)+'px',
		      height: settings.height+'px',
		      marginTop: (settings.marginTop)+'px',
		      opacity: 1
		    });
		    callback();
		},
		showTransition: function(elts, settings, callback){
                    elts.loading
			.css({
				marginTop: elts.contentWrapper.css('marginTop'),
				marginLeft: elts.contentWrapper.css('marginLeft'),
				height: elts.contentWrapper.css('height'),
				width: elts.contentWrapper.width(),
				opacity: 1
			})
			.show();
			elts.contentWrapper.hide();
			callback();
		},
		hideTransition: function(elts, settings, callback){
			elts.loading.hide();
			elts.contentWrapper
			.css({
		      width: settings.width+'px',
		      marginLeft: (settings.marginLeft)+'px',
		      height: settings.height+'px',
		      marginTop: (settings.marginTop)+'px',
		      opacity: 1
			}).show();
			callback();
		},
		endShowContent: function(elts, settings){

            $('#nyroModalContent').width($('#modalContent').width()+20);
            $('#nyroModalContent').parent().width($('#modalContent').width()+20);
            $('#nyroModalContent').parent().parent().width($('#modalContent').width()+20);

			$("#submitButton").focus();

			var link = $("#formsuccess").html();

			if (link != null && link != "") {
                if(link == "currentPage" || link == "reloadMenu")
                {
                    link = window.location.toString();
                }
				var tabLink = link.split("/");
				$.nyroModalRemove();

                reloadSlideMenuContent(tabLink[tabLink.length-2]+'/'+tabLink[tabLink.length-1]);
			}
		},
		hideContent: function(elts, settings, callback){
			elts.contentWrapper.hide();
			callback();
		},
		hideBackground: function(elts, settings, callback){
			elts.bg.hide();
			callback();
		}
	});
}

function resizeMediaDetails()
{
    if($('#imagesCont').height() < $('#folderContent').height())
    {
        $('#mediaDetail').width($('#folderContent').width()-22);
    }
    else
    {
        $('#mediaDetail').width($('#folderContent').width()-38);
    }
}

function getHash(href)
{
	return href.replace(/^.*#/, '');
}

function getLocale(key, params ,lang)
{
    var result;

    $.ajax({
            url: '?module=backoffice&action=AjaxGetLocale',
            data: {key:key, lang:lang, params:params},
            async: false,
            success: function(res)
            {
                result = res;
            }
    });

    return result;
}

/***************************************************************************
 *
 * 					SLIDER MENU
 *
 ***************************************************************************/

/**
 * Get the slider menu actions
 */
function sliderMenu()
{
	$(".slideMenuItem").hover(function(){
        if($(this).children("span.slideMenuItemButtons:first").length) {
            $(this).children("span.slideMenuItemButtons:first").show();
        }
	}, function(){
		$(this).children("span.slideMenuItemButtons:first").hide();
	});

	$(".slideMenuItemButtons").hover(function(){
        if(!$(this).parent(".slideMenuItem:first").hasClass('selected'))
        {
            $(this).parent(".slideMenuItem:first").addClass("slidingMenuHover");
        }
	},function(){
        parent = $(this).parent(".slideMenuItem:first");
        if(!parent.hasClass('selected'))
        {
            $(this).parent(".slideMenuItem:first").removeClass("slidingMenuHover");
        }
	})

	$(".slidingMenu").sortable({
		opacity: 0.6,
		items: '.moveable',
		axis: 'y',
        start: function(event, ui){
            //$(".slideMenuItem a.node").expire('click');
        },
		sort: function(event, ui){
			$(".slidingMenu a").css("cursor", "row-resize");
		},
		stop: function(event, ui){
			$(".slidingMenu a").css("cursor", "pointer");
		},
		update: function(event, ui) {
			$.ajax({
				url: '?module=backoffice&action=sliderMenuItemSort&href='+getHash(location.href)+'&'+$(this).sortable('serialize')
			})
		}
	});

    slidingMenuUpDown();
}

function slidingMenuUpDown()
{
    $('.slideMenu').css('top', '0px');
    if(($('#leftCol').height()) < ($('#slideMenuContainer .slide-menu-left').height()))
    {
        $('.menuSlidingUpDown').show();

        $('#menuDown').mousedown(function()
        {
            t = parseInt($('.slideMenu').css('top').replace('px', ''));
            diff = ($('#left-col').height()-119) - $('#slideMenuContainer .slide-menu-left').height();
            $(this).addClass('menuSlidingUpDownClick');
            if(t > diff)
            {
                $('.slideMenu').css('top', t-16+'px');
            }
        }).mouseup(function(){
            $(this).removeClass('menuSlidingUpDownClick');
        });

        $('#menuUp').mousedown(function()
        {
            $(this).addClass('menuSlidingUpDownClick');
            t = parseInt($('.slideMenu').css('top').replace('px', ''));
            if(t < 0)
            {
                $('.slideMenu').css('top', (t+16)+'px');
            }
        }).mouseup(function(){
            $(this).removeClass('menuSlidingUpDownClick');
        });
    }
    else
    {
        $('.menuSlidingUpDown').hide();
    }
}

/**
 * Slide from right to left - one level up
 * @param {String} href
 */
function slideMenuToUp(href, id)
{
    $.ajax({
        url: 'index.php?module=medias&action=block_MceFolders',
        data: {href: getHash(href)},
        success: function(result)
        {
            $("#slideMenuContainer .slide-menu-right").html(result);
        },
        complete: function()
        {
            $("#slideMenuContainer").css({marginLeft:0});
            $("#slideMenuContainer").animate(
            {marginLeft:"-250px"},
            200,
            'swing',
            function(){
                $("#slideMenuContainer .slide-menu-left").html($("#slideMenuContainer .slide-menu-right").html());
                $("#slideMenuContainer").css({marginLeft:"0px"});

                hashref = id.split('_');
                folderLang = hashref[2];
                folderId = hashref[1];
                loadFolderContent();
                sliderMenu();
            });
        }
    });
}

/**
 * Slide from left to right - history back
 * @param {String} href
 */
function slideMenuToDown(href, id)
{
	$("#slideMenuContainer .slide-menu-right").html($("#slideMenuContainer .slide-menu-left").html());

	$("#slideMenuContainer").css({marginLeft:"-250px"});
    $.ajax({
        url: 'index.php?module=medias&action=block_MceFolders',
        data: {href: getHash(href)},
        success: function(result){
            $("#slideMenuContainer .slide-menu-left").html(result);
        },
        complete: function(){
            $("#slideMenuContainer").animate(
            {marginLeft:"0px"},
            200,
            'swing',
            function()
            {
                $("#slideMenuContainer .slide-menu-right").html("");
                hashref = id.split('_');
                folderLang = hashref[2];
                folderId = hashref[1];
                loadFolderContent();
                sliderMenu();
            });
        }
    })
}

function reloadSlideMenuContent(href)
{
	$("#slideMenuContainer .slide-menu-left").load('?module=medias&action=block_MceFolders&href='+getHash(href), function(){
		sliderMenu();
        getContextMenu();
	});
}

/**
 * Catch click on slider menu items
 */
function liveQuerySliderMenu()
{
	$(".slideMenuItem a.node").live('click', function(event){
        event.preventDefault();

		if(!$(this).hasClass("selected") && !$(this).hasClass('ui-sortable-helper'))
		{
			var link = getHash($(this).attr('href'));

            if($(this).hasClass("noslide"))
            {
                $(".slidingMenu a.selected").removeClass("selected");
                $(this).addClass("selected");
            }

			//Load right column content
			if (link != "#" && link != "")
            {
                $("#loaderContainer").show();

				// Slide menu to upper level
				if ($(this).hasClass("more"))
                {
					slideMenuToUp(link, $(this).attr('id'));
				}

				// Slide menu to lower level
				if ($(this).hasClass("expanded"))
                {
					if ($(this).hasClass("noslide"))
                    {
						return void(0);
					}
					else
                    {
						slideMenuToDown(link, $(this).attr('id'));
					}
				}
				else
				{
					if ($(this).hasClass("noslide"))
                    {
                        return void(0);
					}
				}
			}
		}
	});
}

function liveQuerySliderMenuContext()
{
    $('.slideMenuAddMenu').livequery(function()
    {
        $(this).hover(function(){
            $('#slideMenuHoverContext').html($('#sliderMenuContextMenu').html());

            var pos = $(this).offset();
            var top = pos.top - 2 + "px";

            $('#slideMenuHoverContext').css({
                display: 'block',
                position: 'absolute',
                zIndex: 10,
                top: top
            });

            liveQueryLinks();
        }, function(){
            $('#slideMenuHoverContext').hide();
        });

        $('#slideMenuHoverContext').hover(function(){
            $('#slideMenuHoverContext').show();
        }, function(){
            $('#slideMenuHoverContext').hide();
        });
    });
}

/**
 * Catch click on links in bo
 */
function liveQueryLinks()
{
	$('a.mediaModal, a.nyroModal').live('click', function(event){
        event.preventDefault();

		var href = getHash(this.href);

		if(!$(this).hasClass("nyroModal"))
		{
            if(folderId == null) folderId = folderRoot;
			href = href + "/"+folderLang+"/"+folderId;
        }

		showModal("?module=backoffice&action=AjaxContext&href="+href+"&mce=1");
		return false;
	});
}

/*****************************************************************
 *
 * INIT
 *
 *****************************************************************/

$(document).ready(function(){
    $(window).resize(function(){
        slidingMenuUpDown();
        $('#folderContent').height($(window).height()-73);
        if($('#mediaDetail').css('display') != 'none')
        {
            resizeMediaDetails();
        };
    });

    liveQueryLinks();
    liveQuerySliderMenu();
    liveQuerySliderMenuContext();
	liveQueryTooltips();

	initBrowser();
    
	research();

    $(window).bind('beforeunload', function(){
        window.opener.actionAddImg = "tinyMce";
    });
});